package com.lxl.securitypermission.config.custom;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

/**
 * 细粒度鉴权关键实现 实现url 需要对应的 角色
 */
@Slf4j
@Component
public class CustomPermissionSource implements FilterInvocationSecurityMetadataSource {

  public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
  }

  private AntPathMatcher matcher = new AntPathMatcher();

  /**
   * 此处返回null 鉴权将不会进入 AccessDecisionManager 当做白名单放行
   *
   * @param object
   * @return
   */
  public Collection<ConfigAttribute> getAttributes(Object object) {
    final HttpServletRequest request = ((FilterInvocation) object).getRequest();
    String url = request.getRequestURI();
    //可以使用redis的 hash 存储白名单
    if (matcher.match("/res/**", url) || matcher.match("/xadmin/**", url)) {
      //白名单直接放行， return null; 即可，不会走校验
      return null;
    }

    //任意返回一个值，让鉴权进入 CustomAccessDecisionManager 具体鉴权将在 CustomAccessDecisionManager中
    return SecurityConfig.createList("a");
  }

  public boolean supports(Class<?> clazz) {
    return FilterInvocation.class.isAssignableFrom(clazz);
  }
}
